package com.achievo.reportserver.ds;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;

import com.achievo.reportserver.config.ConfigFactory;


/**
 * 
 * Report Server
 * write at Jan 21, 2010
 * @author <a href="mailto:chinaoryx@gmail.com">Hyman.Zhang (Zhang Haipeng)</a>
 * @version 1.0
 * 
 *
 */
public class DataSourceFactory{
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DataSourceFactory.class);
	
	public static final Map<String, DataSource> dataSourceMap = new Hashtable<String, DataSource>();
	
	
	
	private static final String CONFKEY_PREFIX = "server.datasource";
	
	public static DataSource getDataSource(String name){		
		ConfigFactory.getDatasourceConfig().getString("aa");
		DataSource ds = null;
		ds = dataSourceMap.get(name);
		return ds;
	}
	
	

	
	
	
	public static void addDataSource(String name, DataSource ds){
		dataSourceMap.put(name, ds);
	}
	
	
	
	
	public static void refresh(){
		Collection<DataSource> dsList = dataSourceMap.values();
		for (DataSource dataSource : dsList) {
			if (dataSource instanceof BasicDataSource) {
				BasicDataSource baseDs = (BasicDataSource) dataSource;
				try {
					baseDs.close();
				} catch (SQLException e) {					
					logger.error("BaseDataSource (" + baseDs + ") close fail!",
							e);
				}
			}
		}
		
		dataSourceMap.clear();
		
		
		
		Configuration conf = ConfigFactory.getDatasourceConfig();
		String[] dsNameList = conf.getStringArray(CONFKEY_PREFIX);
		if (dsList != null) {
			for (String dsName : dsNameList) {
				
				StringBuffer preSb = new StringBuffer(CONFKEY_PREFIX);
				preSb.append(".");
				preSb.append(dsName);
				preSb.append(".");
				
				String dsType = null;
				dsType = conf.getString(preSb.toString() + "type");
				
				if ("jdbc".equalsIgnoreCase(dsType)) {
					String url = null;
					String driver = null;
					String password = null;
					String username = null;
					url = conf.getString(preSb.toString() + "url");
					driver = conf.getString(preSb.toString() + "driver");
					username = conf.getString(preSb.toString() + "username");
					password = conf.getString(preSb.toString() + "password");
					BasicDataSource ds = new BasicDataSource();
					ds.setDriverClassName(driver);
					ds.setUrl(url);
					ds.setUsername(username);
					ds.setPassword(password);
					DataSourceFactory.addDataSource(dsName, ds);
					
				}
			}
		}
		
	}


	public static Map<String, DataSource> getDataSourceMap() {
		return dataSourceMap;
	}




}
